# 文件
# 1.文件操作
f = open("D:/python_Test/网页聊天室.txt", "r", encoding="UTF-8")
print(type(f))

# 读取文件 read()
# print(f"读取10个字节:{f.read(10)}")
# 这一次会在上一个read的结尾处开始读取
# print(f"读取全部内容:{f.read()}")

# 读取全部行
print("------------")
# lines = f.readlines()
# print(f"lines对象的内容:{lines}")

# for循环读取文件行
# for line in f:
#     print(f"每一行的数据为:{line}")

# 文件关闭
f.close()

# with open 语法操作文件,可以自动关闭文件
#统计文件内INSERT出现的次数
# with open("D:/python_Test/网页聊天室.txt", "r", encoding="UTF-8") as f:
    # 方法1
    # count = 0
    # for line in f:
    #     count+=line.count("INSERT")
    # print(count)

    # 方法2
    # count = 0
    # for line in f:
    #     line = line.strip()
    #     words = line.split()
    #     for word in words:
    #         if word == "INSERT":
    #             count += 1
    # print(count)


# 写操作
f1 = open("D:/python_Test/网页聊天室.txt", "w", encoding="UTF-8")
#当文件不存在时，会创建文件，当文件存在时，会清空内容
f1.write("hello world")
f1.write(" and hello earth")
f1.flush()

#close，内置了flush方法
f1.close()

# 追加
#文件不存在会创建，如果文件存在，不会清空内容
f2 = open("D:/python_Test/网页聊天室.txt", "a", encoding="UTF-8")
f2.write("hello world")
f2.close()



#文件备份 案例
f = open("D:/python_Test/网页聊天室.txt", "r", encoding="UTF-8")
content = f.read()
f1 = open("D:/python_Test/网页聊天室备份.txt", "w", encoding="UTF-8")
f1.write(content)
f.close()
f1.close()